<template>
    <el-aside width="20%" class="sidebar">
        <div class="sidebar-card">
            <div class="sidebar-header">
                <h1>AI 聊天助手</h1>
                <el-button type="primary" size="small" class="new-chat-btn" @click="createNewChat"> + 新建聊天</el-button>
            </div>
            <div class="sidebar-search">
                <el-input v-model="keyword" placeholder="搜索历史会话..." size="small" clearable />
            </div>
            <div class="section-title">历史会话</div>
            <div class="chat-history">
                <template v-if="filteredConversations.length > 0">
                    <div 
                        v-for="item in filteredConversations" 
                        :key="item.conversation_id" 
                        class="chat-item"
                        @click="selectConversation(item)"
                    >
                        <div class="chat-item-left">
                            <div class="chat-avatar">💬</div>
                            <div class="chat-title">{{ item.title || '未命名会话' }}</div>
                        </div>
                        <div class="chat-actions" @click.stop>
                            <el-button link type="primary" size="small" @click="onRename(item)">修改</el-button>
                            <el-popconfirm 
                                title="确认删除该会话？此操作不可恢复"
                                confirm-button-text="删除"
                                cancel-button-text="取消"
                                confirm-button-type="danger"
                                @confirm="onDelete(item)"
                            >
                                <template #reference>
                                    <el-button link type="danger" size="small">删除</el-button>
                                </template>
                            </el-popconfirm>
                        </div>
                    </div>
                </template>
                <div v-else class="empty-history">
                    <p>暂无聊天记录</p>
                    <p>点击上方"新建聊天"开始对话</p>
                </div>
            </div>
        </div>
    </el-aside>
</template>

<script>
import { apiService } from '@/services/api'
import { ElMessageBox } from 'element-plus'
import { on as onEvent, off as offEvent } from '@/utils/eventBus'

export default {
    name: 'MessagesConversation',
    data() {
        return {
            conversations: [],
            loading: false,
            error: null,
            keyword: ''
        }
    },
    computed: {
        filteredConversations() {
            if (!this.keyword.trim()) return this.conversations
            const k = this.keyword.trim().toLowerCase()
            return this.conversations.filter(c => (c.title || '').toLowerCase().includes(k))
        }
    },
    mounted() {
        this.fetchConversations()
        // 监听新会话创建事件
        this._onCreated = (e) => {
            const id = e && e.detail ? e.detail.conversation_id : null
            this.fetchConversations().then(() => {
                if (id) {
                    // 刷新完成后，若存在新ID则保持选中
                    const found = this.conversations.find(c => Number(c.conversation_id) === Number(id))
                    if (found) {
                        this.selectConversation(found)
                    }
                }
            })
        }
        onEvent('conversation:created', this._onCreated)
    },
    beforeUnmount() {
        if (this._onCreated) offEvent('conversation:created', this._onCreated)
    },
    methods: {
        async fetchConversations() {
            // 避免切换会话时引起闪烁，不再用loading切换UI
            this.loading = true
            this.error = null
            try {
                const res = await apiService.getConversations()
                this.conversations = Array.isArray(res && res.conversations) ? res.conversations : []
            } catch (e) {
                console.error('获取会话列表失败:', e)
                this.error = e
            } finally {
                this.loading = false
            }
        },
        formatTime(date) {
            if (!date) return ''
            const d = new Date(date)
            if (isNaN(d.getTime())) return ''
            return d.toLocaleString('zh-CN', {
                month: '2-digit', day: '2-digit',
                hour: '2-digit', minute: '2-digit'
            })
        },
        selectConversation(item) {
            this.$router.push({ name: 'home', query: { conversation_id: item.conversation_id }})
            this.$emit('select-conversation', item)
        },
        createNewChat() {
            this.$router.push({ name: 'home' })
            this.$emit('create-new-chat')
        },
        async onDelete(item) {
            try {
                await apiService.deleteConversation(item.conversation_id)
                // 若当前在被删会话中，重置到新建聊天
                const currentId = Number(this.$route.query.conversation_id)
                if (currentId === Number(item.conversation_id)) {
                    this.$router.push({ name: 'home' })
                    this.$emit('create-new-chat')
                }
                await this.fetchConversations()
            } catch (e) {
                console.error('删除会话失败:', e)
                this.$message.error('删除失败，请稍后重试')
            }
        },
        async onRename(item) {
            try {
                const { value } = await ElMessageBox.prompt('请输入新的会话标题', '修改标题', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    inputValue: item.title || '',
                    inputPlaceholder: '新的标题'
                })
                const newTitle = (value || '').trim()
                if (!newTitle) return
                await apiService.updateConversationTitle(item.conversation_id, newTitle)
                await this.fetchConversations()
                // 如果当前会话就是被改名的，更新路由不变，仅刷新左侧
                this.$message.success('标题已更新')
            } catch (e) {
                if (e === 'cancel' || e === 'close' || (e && e.action && (e.action === 'cancel' || e.action === 'close'))) return
                console.error('修改标题失败:', e)
                this.$message.error('修改失败，请稍后重试')
            }
        }
    }
}
</script>

<style scoped>
.sidebar {
    height: calc(100vh - var(--header-height));
    background: transparent;
    color: var(--text);
    display: flex;
    flex-direction: column;
    padding: 16px 8px 16px 16px;
    overflow: hidden;
    box-sizing: border-box;
    min-height: 0;
}

.sidebar-card{
    background: var(--sidebar-bg);
    border: 1px solid var(--border);
    border-radius: 16px;
    box-shadow: var(--shadow-sm);
    padding: 12px 12px 8px;
    display: flex;
    flex-direction: column;
    gap: 12px;
    height: 100%;
    min-height: 0;
    box-sizing: border-box;
}

.sidebar-header {
    display: flex;
    align-items: center;
    gap: 8px;
    justify-content: space-between;
    padding: 6px 4px 10px;
    border-bottom: 1px dashed var(--border);
}

.sidebar-header h1 {
    font-size: 18px;
    font-weight: 700;
    letter-spacing: .2px;
}

.new-chat-btn {
    background-color: var(--accent);
    border: none;
    color: #ffffff;
    box-shadow: 0 6px 18px rgba(61,85,236,.25);
}

.new-chat-btn:hover {
    filter: brightness(1.05);
}

.sidebar-search{
    padding: 0 4px;
}

.section-title{
    padding: 6px 4px 0;
    font-size: 12px;
    color: var(--muted);
}

.chat-history {
    flex: 1;
    overflow-y: auto;
    padding: 6px 4px 8px;
    display: flex;
    flex-direction: column;
    gap: 8px;
    min-height: 0;
}

.chat-item {
    padding: 10px 12px;
    border-radius: 12px;
    border: 1px solid var(--border);
    background: #fff;
    cursor: pointer;
    transition: all .2s ease;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-shadow: 0 2px 10px rgba(16,24,40,.04);
}

.chat-item-left{
    display: flex;
    align-items: center;
    gap: 10px;
    flex: 1;
    min-width: 0;
}

.chat-avatar{
    width: 26px;
    height: 26px;
    border-radius: 8px;
    background: linear-gradient(135deg, var(--accent), var(--accent-2));
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    box-shadow: 0 6px 14px rgba(61,85,236,.25);
}

.chat-item:hover {
    background-color: #3d55ec;
    color: #fff;
    border-color: transparent;
    transform: translateY(-1px);
}

.chat-item.active {
    background-color: #ff932f;
    border: 1px solid #fafafa;
    color: #1f2937;
}

.chat-title {
    font-size: 14px;
    color: #000000;
    flex: 1;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    min-width: 0;
    line-height: 1.2;
}

.chat-item:hover .chat-title {
    color: #fff;
}

.chat-time {
  font-size: 12px;
  color: #ffffff;
  margin-left: 10px;
}

.chat-actions{ 
  display: flex; 
  align-items: center; 
  gap: 6px; 
  opacity: 0; 
  pointer-events: none; 
  transition: opacity .15s ease;
  flex-shrink: 0;
  justify-content: flex-end;
  padding-left: 8px;
  min-width: 80px;
}

.chat-item:hover .chat-actions{ 
  opacity: 1; 
  pointer-events: auto; 
}

/* 确保按钮在hover状态下的样式 */
.chat-actions .el-button {
  font-size: 12px;
  padding: 2px 6px;
  height: 24px;
  min-height: 24px;
  border-radius: 4px;
}

.chat-item:hover .chat-actions .el-button {
  background-color: rgba(255, 255, 255, 0.1);
  border-color: rgba(255, 255, 255, 0.2);
  color: #fff;
}

.chat-item:hover .chat-actions .el-button:hover {
  background-color: rgba(255, 255, 255, 0.2);
  border-color: rgba(255, 255, 255, 0.3);
  transform: scale(1.05);
}

/* 空历史记录样式 */
.empty-history {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  text-align: center;
  padding: 24px 12px;
  color: var(--muted);
}

.empty-history p {
  margin: 6px 0;
  font-size: 13px;
  line-height: 1.4;
}

.empty-history p:first-child {
  font-weight: 600;
  color: var(--text);
  font-size: 14px;
}

/* 聊天记录滚动条样式 */
.chat-history::-webkit-scrollbar {
  width: 6px;
}

.chat-history::-webkit-scrollbar-track {
  background: transparent;
}

.chat-history::-webkit-scrollbar-thumb {
  background: linear-gradient(180deg, var(--accent), var(--accent-2));
  border-radius: 3px;
}

.chat-history::-webkit-scrollbar-thumb:hover {
  filter: brightness(1.05);
}
</style>

